package com.jeecg.p3.system.poster.web;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Course;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.poster.entity.PosterType;
import com.jeecg.p3.system.poster.entity.ExamQuestion;
import com.jeecg.p3.system.poster.service.ExamQuestionService;
import com.jeecg.p3.system.poster.service.PosterTypeService;
import com.jeecg.p3.system.service.CourseService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.util.HtmlUtil;
import com.jeecg.p3.system.util.UuidUtils;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.Date;
import java.util.List;

/**
 *
 * @ClassName: ExamQuestionBankController
 * @Description: TODO 题库控制层
 * @author: zhangxiao
 * @date: 2020年12月8日 下午7:29:38
 */
@Controller
@RequestMapping("/system/back/poster/examQues")
public class ExamQuestionController extends BaseController {
    public final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ExamQuestionService service;//试卷服务层
    @Autowired
    private CourseService courseService;//课时服务层
    @Autowired
    private ProductService productService;//课程服务层
    @Autowired
    private PosterTypeService posterTypeService;

    /**
     *
     * @param query 分页查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute ExamQuestion query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<ExamQuestion> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        pageQuery.setQuery(query);
        velocityContext.put("examQues",query);
        List<Product> lstProduct = productService.find();
        velocityContext.put("lstProduct",lstProduct);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        String viewName = "system/back/exam/exam_ques_list.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public void toAddDialog(HttpServletRequest request, HttpServletResponse response, ModelMap model)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        List<Product> products = productService.find();
        velocityContext.put("products", products);
        if(products != null && products.size() > 0) {
            List<Course> courses = courseService.listCourseByProductId(products.get(0).getId());
            velocityContext.put("courses", courses);
        }
        String viewName = "system/back/exam/exam_ques_add.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson doAdd(@ModelAttribute ExamQuestion examQuestion, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            ExamQuestion param = new ExamQuestion();
            param.setCourse(examQuestion.getCourse());
            List<ExamQuestion> list = service.findByParam(param);
            //如果该课时已存在试题，则不允许在添加
            if(list != null) {
                if(list.size() > 0) {
                    j.setSuccess(false);
                    j.setMsg("该课时已存在试题，请查看!");
                    return j;
                }
            }
            String fileUrl = ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.examQues;
            String fileDir = uploadConfig.getUploadPath() + user.getId() + ComCode.examQues;
            String toUrl = ComCode.systemUrl + "/system/back/poster/examResult/toStartExam.do?courseId=" + examQuestion.getCourse().getId();
            String qrcodePath = createQrCode(toUrl, fileUrl, fileDir, UuidUtils.getId() + ".jpg", false).getFileDir();
            String qrName = UuidUtils.getId() + ".jpg";
            PosterType pt = this.posterTypeService.findByCode("kst01");
            if(pt != null) {
                HtmlUtil.convertImage(pt.getBackPath(), pt.getBackWidth(), pt.getBackHeight(),
                        qrcodePath,  pt.getQrCodeWidth(), pt.getQrCodeHeight(),
                        pt.getxPositon(), pt.getyPositon(), fileDir + qrName,
                        true, "黑体", 30, new Color(205,48,48),
                        examQuestion.getTitle(), 0, 150);
                examQuestion.setQrcode(fileUrl + qrName);
            }
            examQuestion.setCreateDate(DateUtil.dateToString(new Date()));
            examQuestion.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            examQuestion.setCreateUser(user.getId());
            examQuestion.setStatus("1");
            service.doAdd(examQuestion);
            j.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }


    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="/toEdit",method = RequestMethod.GET)
    public void toEdit(@RequestParam(required = true, value = "id" ) String id,HttpServletResponse response,
                       HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        ExamQuestion examQuestion = service.findById(id);
        velocityContext.put("examQues", examQuestion);
        //查询课程
        List<Product> products = productService.find();
        velocityContext.put("products", products);
        //查询当前课时所在课时列表
        List<Course> courses = courseService.listCourseByProductId(examQuestion.getCourse().getProduct().getId());
        velocityContext.put("courses", courses);
        String viewName = "system/back/exam/exam_ques_edit.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存修改数据
     * @return
     */
    @RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute ExamQuestion examQuestion, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            ExamQuestion param = new ExamQuestion();
            param.setCourse(examQuestion.getCourse());
            List<ExamQuestion> list = service.findByParam(param);
            //如果该课时已存在试题，则不允许在添加
            if(list != null) {
                if(list.size() > 1) {
                    j.setSuccess(false);
                    j.setMsg("该课时已存在试题，请查看!");
                    return j;
                } else if(list.size() == 1) {
                    if(!examQuestion.getId().equals(list.get(0).getId())) {
                        j.setSuccess(false);
                        j.setMsg("该课时已存在试题，请查看!");
                        return j;
                    }
                }
            }
            String fileUrl = ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.examQues;
            String fileDir = uploadConfig.getUploadPath() + user.getId() + ComCode.examQues;
            String toUrl = ComCode.systemUrl + "/system/back/poster/examResult/toStartExam.do?courseId=" + examQuestion.getCourse().getId();
            String qrcodePath = createQrCode(toUrl, fileUrl, fileDir, UuidUtils.getId() + ".jpg", false).getFileDir();
            String qrName = UuidUtils.getId() + ".jpg";
            PosterType pt = this.posterTypeService.findByCode("kst01");
            if(pt != null) {
                HtmlUtil.convertImage(pt.getBackPath(), pt.getBackWidth(), pt.getBackHeight(),
                        qrcodePath,  pt.getQrCodeWidth(), pt.getQrCodeHeight(),
                        pt.getxPositon(), pt.getyPositon(), fileDir + qrName,
                        true, "黑体", 30, new Color(205,48,48),
                        examQuestion.getTitle(), 0, 150);
                examQuestion.setQrcode(fileUrl + qrName);
            }
            examQuestion.setUpdateDate(DateUtil.dateToString(new Date()));
            examQuestion.setUpdateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            examQuestion.setUpdateUser(getCurrentUser(request).getId());
            this.service.doEdit(examQuestion);
            j.setMsg("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value="/doDelete",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) String id, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            ExamQuestion examQuestion = service.findById(id);
            examQuestion.setDeleteDate(DateUtil.dateToString(new Date()));
            examQuestion.setDeleteTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            examQuestion.setDeleteUser(user.getId());
            service.doDelete(examQuestion);
            j.setMsg("删除成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("删除失败:"+e.getMessage());
        }
        return j;
    }
}
